package com.api.service;

import com.api.cache.CacheTemplate;
import com.api.mapper.TUserMapper;
import com.api.model.TUser;
import com.api.utils.PasswordHelper;
import com.api.utils.TokenCacheUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * Created by PC on 2017/7/12.
 */
@Service
public class UserService extends BaseService {
    private TUserMapper userMapper;
    private static final String Password = "111111";
    private static final String QINIU_URL = "http://oso99h11v.bkt.clouddn.com/face";
    @Autowired
    private CacheTemplate cacheTemplate;

    @Autowired
    public void setUserMapper(TUserMapper userMapper) {
        this.userMapper = userMapper;
        super.baseMapper = userMapper;
    }

    public String getName() {
        return "ndq_" + getRandomString(6);
    }

    public String getRandomString(int length) { //length表示生成字符串的长度
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public String getRandomNumString(int length) { //length表示生成字符串的长度
        String base = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public String getRandomNumString(int length, String base) { //length表示生成字符串的长度
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }

    public String getPassword() {
        String password = PasswordHelper.md5(Password);
        return PasswordHelper.md5("ndq" + password + "ndq");
    }

    public String getFace() {
        String num = getRandomNumString(1, "12345");
        return QINIU_URL + num + ".jpg";
    }

    public TUser findUserByToken(String token) {
        Integer userId = TokenCacheUtils.getUserIdByToken(cacheTemplate, token);
        if (userId == null) {
            return null;
        }
        return (TUser) findObjByKey(userId);
    }
}
